package by.bsuir.web.tags;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import by.bsuir.util.Node;

public class TreeTag extends TagSupport {

    private static final long serialVersionUID = 1L;

    private Node node;

    public void setNode(Node node) {
        this.node = node;
    }

    @Override
    public int doStartTag() throws JspException {
        try {
            JspWriter out = pageContext.getOut();
            out.println(" <ul id=\"browser\" class=\"filetree\">");
            out.println("<c:set var=\"previousLevel\" value=\"0\"/>");
            out.println("<granizo:tree tree=\"${node}\" connectMethod=\"getNodes\" var=\"status\">");
            out.println("<granizo:startElement>");
            out.println("<c:if test=\"${previousLevel < status.level}\">");
            out.println("<ul>");
            out.println("</c:if>");
            out.println("<c:if test=\"${status.element.folder}\">");
            out.println("<li><span class=\"folder\">${status.element.name}</span>");
            out.println("</c:if>");
            out.println("<c:if test=\"${status.element.file}\">");
            out.println("<li><span class=\"file\">${status.element.name}</span>");
            out.println("</c:if>");
            out.println("</granizo:startElement>");
            out.println("<granizo:endElement>");
            out.println("<c:if test=\"${previousLevel > status.level}\">");
            out.println("</ul>");
            out.println("</c:if>");
            out.println("</li>");
            out.println("</granizo:endElement>");
            out.println("<c:set var=\"previousLevel\" value=\"${status.level}\"/>");
            out.println("</granizo:tree>");
            out.println("</ul>");
        } catch (IOException ioe) {
            throw new JspException("Error: IOException while writing to client"
                                   + ioe.getMessage());
        }
        return SKIP_BODY;
    }

    @Override
    public int doEndTag() throws JspException {
        return SKIP_PAGE;
    }

}
